package com.wy2.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wy2.entity.Clock;
import com.wy2.entity.Student;
import com.wy2.entity.User;
import com.wy2.mapper.StudentMapper;
import com.wy2.mapper.UserMapper;
import com.wy2.service.ClockService;
import com.wy2.service.StudentService;
import com.wy2.service.UserService;
import com.wy2.util.QuanZhongUtil;

import lombok.extern.slf4j.Slf4j;


/**
 * 需要执行的定时任务
 * 
 * @author dell
 *
 */

@Slf4j
@Component
@Service
public class ExecutePro implements Runnable {
	
	@Autowired
	private UserMapper userMapper;

	@Autowired
	private StudentMapper studentMapper;

	private static Random random = new Random();

	@Override
	public void run() {
		System.out.println("正在启动中.....................");
		//时间格式转换
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		//new一个新的时间对象
		Date time = new Date();
		//获取当前的年月日
		String times = dateFormat.format(time);
		System.out.println("--times--"+times);
		//查询出当日签到用户
		List<QuanZhongUtil> ulist = userMapper.findByIntime(times);
		System.out.println("--ulist--"+ulist);
		//定义变量weightSum 让初始的权重和为0
		Integer weightSum = 0;
		//遍历所有今日已签到咨询师
		for (QuanZhongUtil wc : ulist) {
			//将咨询师的权重相加
			weightSum += wc.getWeight();
		}
		//查询所有没有分配的学生
		List<Student> slist = studentMapper.findByZxName("未分配");
		System.out.println("--slist--"+slist);
		//如果没有分配的学生集合大于0
		if (slist.size() > 0) {
			//遍历所有没有分配的学生
			for (Student stu : slist) {
				//获取遍历到学生的id
				Integer sid = stu.getSid();
				//如果咨询师权重和小于0的时候
				if (weightSum <= 0) {
					// return 4; // "暂时没有相关人员打卡"
					System.out.println("暂时没有相关人员打卡");
				}
				//随机一个0~权重和之间的数
				Integer n = random.nextInt(weightSum); // n in [0, weightSum)
				//定义变量m为0
				Integer m = 0;
				//定义变量ask为未分配
				String ask = "未分配";
				//循环遍历咨询师
				for (QuanZhongUtil wc : ulist) {
					//判断随机生成的权重数是否为遍历到的咨询师，如果是执行
					if (m <= n && n < m + wc.getWeight()) {
						//将随机咨询师存入ask
						ask = wc.getUname();
						break;
						//立即跳出循环
					}
					//计算权重值的和
					m += wc.getWeight();
				}
				//将获取到咨询师存入相应字段，进行分量
				studentMapper.updateZxNameById(ask, sid);
				System.out.println("--ask--"+ask+"--sid--"+sid);
			}
			// return 2;//"完成分配"
			System.out.println("完成分配");
		}
		// return 3; //"没有需要分配的学生"
		System.out.println("没有需要分配的学生");

	}

}
